//
//  UserAccount.swift
//  Weibo
//
//  Created by apple on 15/12/16.
//  Copyright © 2015年 Leon. All rights reserved.
//

import UIKit

class UserAccount: NSObject ,NSCoding {
    
    var access_token: String?
    //token生命周期 单位是秒
    var expires_in: NSTimeInterval = 0 {
        didSet{
            //当过期时间一旦被设置 就立即设置expires_date
            expires_date = NSDate(timeIntervalSinceNow: expires_in)
        }
    }
    //token的过期日期  开发者账号是 5 年  普通用户是 3 天
    var expires_date: NSDate?
    //授权用户的uid
    var uid: String?
    //友好显示名称
    var name :String?
    //用户头像  大图
    var avatar_large: String?
    
    //KVC
    init(dict:[String : AnyObject]) {
        super.init()
        self.setValuesForKeysWithDictionary(dict)
    }
    
    override func setValue(value: AnyObject?, forUndefinedKey key: String) {}
    
    override var description: String {
        let key = ["access_token","expires_in","uid","name","avatar_large"]
        return dictionaryWithValuesForKeys(key).description
    }
    //保存自定义对象
    func saveAccount() {
        //在xcode7中没有字符串拼接方法  需要转换为NSString
        let path = (NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).last! as NSString).stringByAppendingPathComponent("account.plist")
        NSKeyedArchiver.archiveRootObject(self, toFile: path)
        
    }
    //类方法   从磁盘解档数据
    class func loadAccount () -> UserAccount?{
        let path = (NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).last! as NSString).stringByAppendingPathComponent("account.plist")
        if let account = NSKeyedUnarchiver.unarchiveObjectWithFile(path) as? UserAccount{
            
            //对用户token进行判断 如果过期 就返回nil
            if account.expires_date?.compare(NSDate()) == NSComparisonResult.OrderedDescending {
                
                return account
                
            }
            
        }
        return nil
    }
    
    
    //解档操作   将磁盘中的二进制数据 -> 自定义对象   和反序列化类似
    required init?(coder aDecoder: NSCoder) {
        // as? 还是使用 as! 具体要看 接收或者需要使用的类型是可选还是必选
        access_token = aDecoder.decodeObjectForKey("access_token") as? String
        //如果基本数据类型 就可以直接获取到具体类型的熟悉 不需要类型转换
        expires_in = aDecoder.decodeDoubleForKey("expires_in")
        uid = aDecoder.decodeObjectForKey("uid") as? String
        avatar_large = aDecoder.decodeObjectForKey("avatar_large") as? String
        name = aDecoder.decodeObjectForKey("name") as? String
        expires_date = aDecoder.decodeObjectForKey("expires_date") as? NSDate
    }
    
    //归档操作  将自定义对象 -> 二进制数据  和序列化类似
    func encodeWithCoder(aCoder: NSCoder) {
        aCoder.encodeObject(access_token, forKey: "access_token")
        aCoder.encodeDouble(expires_in, forKey: "expires_in")
        aCoder.encodeObject(uid, forKey: "uid")
        aCoder.encodeObject(avatar_large, forKey: "avatar_large")
        aCoder.encodeObject(name, forKey: "name")
        aCoder.encodeObject(expires_date, forKey: "expires_date")
    }
    
}
